#!/bin/bash

if [ "`whoami`" != "root" ]; then
	echo 'need root!'
	exit
fi

#停止数据库连接
function stop_pgsql_connects() { 
    processes="`ps aux | grep -v grep | grep 'postgres: postgres' | awk '{ print $2 }'`"
    for p in $processes 
    do
        echo $p
    done
}

#启动数据库
function start_pgsql() { 
	pid=`ps aux | grep 'postgres -D' | grep -v grep | awk '$1 == "postgres" { print $2 }'`
	if [ "$pid" == "" ]; then
		sudo /usr/local/pgsql/bin/pg_start
	fi
}

#导入数据库
function import_db() { 
	if [ ! -f /usr/local/pgsql/bin/psql ]; then
		echo 'file does not esists: /usr/local/pgsql/bin/psql'
		exit
	fi

	if [ ! -f db.tar.gz ]; then
		echo 'Backup file does not exists: db.tar.gz'
		exit
	fi

	echo 'Uncompressing file ... '
	tar zxf db.tar.gz


	db="jc_master"
	if [ -f ./db.sql ]; then
		/usr/local/pgsql/bin/dropdb -h localhost -p 5432 -U postgres ${db}
		echo " -- deleted database: ${db}"
		/usr/local/pgsql/bin/createdb -h localhost -p 5432 -U postgres ${db}
		echo " -- created database: ${db}"
		/usr/local/pgsql/bin/psql -U postgres ${db} < ./db.sql
		echo " -- imported: ${db}"
	else
		" -- file does not exists: db.sql"
	fi

	rm -rf db.sql

	echo 'Imported.'
}

start_pgsql
stop_pgsql_connects
import_db
